<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\models\{ContractApply, ContractSell, ContractList};
use think\Db;
use app\facade\Redis;

class ContractApplys extends Command
{
    protected function configure()
    {
        $this->setName('ContractApplys')->setDescription('申请合约发放');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $cmd = "ps aux | grep '/www/server/php/72/bin/php /www/wwwroot/rskj/think ContractApplys'|grep -v 'grep'| awk '{print $2}'";
        exec($cmd, $ps, $ret);
        if (count($ps) > 1) {
            die("batch of  is running");
        }
        ini_set('max_execution_time', 0);
        $list = (new ContractApply())->where(['type' => 1, 'status' => 2, 'ishave' => 1])->limit(100)->select();
        foreach ($list as $lists) {
            $contrant = (new ContractList())->where('id', $lists['contractid'])->find();
            if (!empty($contrant)) {
                Db::startTrans();
                try {
                    (new ContractApply())->where(['id' => $lists['id'], 'ishave' => 1])->update(['ishave' => 2]);
                    (new ContractSell())->insert([
                        'user_id' => $lists['user_id'],
                        'product_id' => $contrant['id'],
                        'product_name' => $contrant['name'],
                        'buyprice' => $lists['money'],
                        'price' => $lists['money'],
                        'status' => 1
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    dump($e->getMessage());
                    continue;
                }
                echo '成功';
            }
        }
    }
}
